package com.sinosoft.hydra.um.domain.model;

import com.sinosoft.hydra.um.domain.permission.TProcessRecord;
import cn.com.sinux.spring.utils.ValidatorUtils;;
import org.apache.commons.lang.time.DateFormatUtils;

import java.util.*;

/**
 * Created by Administrator on 2016/7/19.
 */
public class LabChart {

    private List<TProcessRecord> records;

    public LabChart(List<TProcessRecord> records) {
        this.records = records;
    }

    public Map<String, Integer> getProcessCounter() {
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (TProcessRecord processRecord : records) {
            Integer r = map.get(processRecord.gettProcessTemplate().getProcessName());
            if (r == null) {
                r = 0;
            }
            r += ValidatorUtils.isArrayEmpty(processRecord.getTeBoms()) ? 0 : processRecord.getTeBoms().size();
            map.put(processRecord.gettProcessTemplate().getProcessName(), r);
        }
        return map;
    }

    public Map<String, Map<String, Integer>> getTimeDataCounter() {
        Map<String, Map<String, Integer>> map = new HashMap<String, Map<String, Integer>>();
        //第一次遍历获取最大时间和最小时间
        Date begin = null;
        for (TProcessRecord processRecord : records) {
            if (begin == null || begin.after(processRecord.getOperateTime())) {
                begin = processRecord.getOperateTime();
            }
            map.put(processRecord.gettProcessTemplate().getProcessName(), new TreeMap<String, Integer>());
        }
        if (begin == null) {
            return Collections.emptyMap();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(begin);
        int year = calendar.get(Calendar.YEAR), month = calendar.get(Calendar.MONTH) + 1;
        calendar.setTime(new Date());
        int endYear = calendar.get(Calendar.YEAR), endMonth = calendar.get(Calendar.MONTH) + 1;
        while (year <= endYear) {
            if (month > 12) {
                month -= 12;
                year++;
            }
            for (String n : map.keySet()) {
                map.get(n).put(year + "-" + (month > 9 ? month : ("0" + month)), 0);
            }
            if (year == endYear && month == endMonth) {
                break;
            }
            month++;
        }
        for (TProcessRecord processRecord : records) {
            String time = DateFormatUtils.format(processRecord.getOperateTime(), "yyyy-MM");
            Map<String, Integer> counter = map.get(processRecord.gettProcessTemplate().getProcessName());
            counter.put(time, counter.get(time) + 1);
            map.put(processRecord.gettProcessTemplate().getProcessName(), counter);
        }
        return map;
    }
}
